package com.ios.palette.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ios.palette.domain.Comment;
import com.ios.palette.domain.User;
import com.ios.palette.respVO.Result;
import com.ios.palette.domain.Status;
import com.ios.palette.service.ICommentService;
import com.ios.palette.service.IStatusService;

/**
 * @author 志刚
 *
 */
@Controller
@RequestMapping(value = "/comment/")
public class CommentController {
	@Autowired
	private ICommentService commentService;
	@Autowired
	private IStatusService workService;

	/**
	 * @param work
	 * @param text
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "add")
	@ResponseBody
	public Result addComment(@RequestBody Status work, @RequestParam String text, HttpServletRequest request)
			throws Exception {
		Result result = new Result("201", "评论失败", null);
		if (text == null) {
			result.setStatus("201");
			result.setMsg("评论为空");
			result.setData(null);
			return result;
		}
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
		String time = sdf.format(date);
		User user = (User) request.getSession().getAttribute("user");
		Comment comment = new Comment();
		comment.setText(text);
		comment.setTime(time);
		comment.setUser(user);
		if (commentService.add(comment) != null) {
			Set<Comment> set = new HashSet<>();
			if (work.getComments() != null)
				set = work.getComments();
			set.add(comment);
			work.setComments(set);
			workService.update(work);
			result.setStatus("200");
			result.setMsg("评论成功");
			result.setData(comment);
		}
		return result;
	}

	/**
	 * @param comment
	 * @return
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public Result delete(@RequestBody Comment comment) throws Exception {
		Result result = new Result("201", "删除失败", null);
		commentService.delete(comment);

		result.setStatus("200");
		result.setMsg("删除成功");
		result.setData(null);
		return result;
	}

}
